package com.zlf.sb.demo.config;

import com.sun.corba.se.spi.orbutil.threadpool.ThreadPoolManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * <b>description</b>： Java高并发、微服务、性能优化实战案例100讲，视频号：程序员路人 <br/>
 * <b>time</b>：2024/4/2 15:16 <br>
 * <b>author</b>：ready likun_557@163.com
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
public class ThreadPoolConfiguration {
    /**
     * 发送邮件用到的线程池
     *
     * @return
     */
/*    @Bean
    public ThreadPoolTaskExecutor emailThreadPool() {
        return ThreadPoolManager.newThreadPool("queryBatchPool", 10, 20, 1000);
    }*/
    @Bean(name = "handleDataPool")
    public ThreadPoolTaskExecutor handleDataPool() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        int core = Runtime.getRuntime().availableProcessors();
        log.info("核心线程数>>>>{}", core);
        taskExecutor.setCorePoolSize(core);//设置核心线程数
        taskExecutor.setMaxPoolSize(core * 2 + 1);//设置最大线程数
        taskExecutor.setKeepAliveSeconds(300);//除核心线程外的线程存活时间
        taskExecutor.setQueueCapacity(5000);//如果传入值大于0，底层队列使用的是LinkedBlockingQueue
        taskExecutor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor executor) -> {
                    if (!executor.isShutdown()) {
                        try {
                            executor.getQueue().put(r);
                        } catch (InterruptedException e) {
                            log.error(e.toString(), e);
                            Thread.currentThread().interrupt();
                        }
                    }
                }
        );
        taskExecutor.setThreadNamePrefix("handleDataPool-");
        taskExecutor.initialize();
        return taskExecutor;
    }

}
